<template>
  <div>
    <!-- 新增、明细、编辑 -->
    <div :style="{
      'padding-bottom': '40px'
    }">
      <FormPanel
        ref="formPanel"
        :list="formList"
        :cols="3"
        :formType="type"
        labelWidth="90"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />
    </div>
    <BaseDialog
        :visible.sync="visible"
        title="销售订单选择"
        destroyOnClose
        width="850px"
        :containerStyle="{height: '100%', overflow: 'auto'}">
        <ViNoSelect @closeViNo="closeViNoHandler"></ViNoSelect>
    </BaseDialog>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button v-if="type == 'show'" @click="closeDialog">返 回</el-button>
      <el-button v-if="type != 'show'" @click="closeDialog">取 消</el-button>
      <el-button v-if="type != 'show'" @click="saveDialog" type="primary">保 存</el-button>
    </div>
  </div>
</template>

<script>
import { postSoInvoice, queryInvoiceById, queryOrderVinInvoice, querySalesOrderVin } from '@/api/capitalsettle/saleSettlement/ordermanage';
import { dictionary } from '@/utils/dictMixin';
import ViNoSelect from './viNoSelect'
import moment from 'moment';
import { notifyAction } from '@/utils';
import { invoice, invoice8} from '@/utils/validate';
export default {
  name: 'DriveModal',
  mixins: [dictionary],
  components: {
    ViNoSelect
  },
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.saveData = null;
    return {
      formList: this.createFormList(), //上方明细数据
      visible: false,
      preParams: {},
      whiteList: ['invoiceChargeType', 'invoiceKind'],
      soVinId: null,
      recordVersion: 0
    };
  },
  created () {
  },
  mounted () {
    if (this.type === 'edit' || this.type === 'show') {
      this.init();
    }
  },
  methods: {
    init() {
      const { rowData, preDateHandler, whiteList } = this;
      queryInvoiceById(rowData.soInvoiceId).then(res => {
        console.log(res,"返回数据")
        this.preParams = res.data;
        this.soVinId = res.data['soVinId']
        this.recordVersion = res.data['recordVersion']
        this.formList.forEach(item => {
          if (item.fieldName === 'invoiceDate') {
            item.initialValue = preDateHandler(res.data[item.fieldName])
          } else if (item.fieldName === 'urls'){
            let urls = res.data['urls']
            if (urls && urls.length > 0) {
              /* let origin = urls.split('/');
              let fileName = origin[origin.length-1];
              item.initialValue.push({ name: fileName, url: urls}) */
              urls.forEach(x=>{
                item.initialValue.push({ name: x.name, url: x.url})
              })
            }
          } else if (whiteList.includes(item.fieldName)){
            item.initialValue = (res.data[item.fieldName] && typeof res.data[item.fieldName]!='number')? Number(res.data[item.fieldName]) : res.data[item.fieldName]
          } else {
            item.initialValue = res.data[item.fieldName];
          }
        })
      });
    },
    createFormList() { //上方明细数据
      return [
        {
          type: 'INPUT',
          label: '销售订单号',
          fieldName: 'viNo',
          placeholder: '',
          disabled: ['edit','show'].includes(this.type) ? true: false,
          readonly: true,
          rules: [{ required: true, message: '请选择订单号', trigger: 'blur' }],
          unitRender: props => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.viNoSelect}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '',
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '费用类型',
          disabled: false,
          fieldName: 'invoiceChargeType',
          placeholder: '请选择...',
          initialValue: '',
          itemList: this.createDictList('1421'),
          rules: [{ required: true, message: '请选择费用类型', trigger: 'change' }],
          disabled: this.type === 'show' ? true: false,
        },
        {
          type: 'INPUT',
          label: '发票号码',
          fieldName: 'invoiceNo',
          placeholder: '',
          maxlength:8,
          rules: [{ required: true, validator: invoice8, trigger: 'blur' },{ required: true, message: '发票号码不能为空', trigger: 'blur' }],
          disabled: this.type === 'show' ? true: false,
        },
        {
          type: 'INPUT',
          label: '发票代码',
          fieldName: 'invoiceCode',
          placeholder: '',
          maxlength:12,
          rules: [{ required: true, validator: invoice, trigger: 'blur' },{ required: true, message: '发票代码不能为空', trigger: 'blur' }],
          disabled: this.type === 'show' ? true: false,
        },
        {
          type: 'SELECT',
          label: '发票类型',
          disabled: false,
          fieldName: 'invoiceKind',
          placeholder: '请选择...',
          initialValue: '',
          itemList: this.createDictList('1207'),
          rules: [{ required: true, message: '请选择发票类型', trigger: 'change' }],
          disabled: this.type === 'show' ? true: false,
        },
        {
          type: 'INPUT_NUMBER',
          label: '发票金额',
          fieldName: 'invoiceAmount',
          placeholder: '',
          rules: [{ required: true, message: '请填写发票金额', trigger: 'blur' }],
          disabled: this.type === 'show' ? true: false,
        },
        {
          type: 'INPUT',
          label: '开票客户',
          fieldName: 'invoiceCustomer',
          placeholder: '',
          rules: [{ required: true, message: '请填写开票客户', trigger: 'blur' }],
          disabled: this.type === 'show' ? true: false,
        },
        {
          type: 'DATE',
          label: '开票日期',
          fieldName: 'invoiceDate',
          dateType:"exactdate",
          placeholder: '',
          rules: [{ required: true, message: '请选择开票日期', trigger: 'blur' }],
          disabled: this.type === 'show' ? true: false,
        },
        {
          type: 'INPUT',
          label: '经办人',
          fieldName: 'transactor',
          placeholder: '',
          initialValue: '',
          rules: [{ required: true, message: '请填写经办人', trigger: 'blur' }],
          disabled: this.type === 'show' ? true: false,
          // itemList: this.createDictList('1429'),
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          placeholder: '',
          rules: [{}],
          selfCols: 2,
        },
        {
          type: 'UPLOAD_FILE',
          label: '上传发票',
          fieldName: 'urls',
          selfCols: 3,
          placeholder: '上传发票...',
          style: {width: '300px'},
          change:val=>{
            console.log(val,"上传发票")
            if(this.type != 'show'){
              if(val && val.length == 4){
                this.formList.find(x=>x.fieldName == 'urls').disabled =true
              }else{
                this.formList.find(x=>x.fieldName == 'urls').disabled =false
              }
            }
          },
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 4,
            tipText: '最多上传4个附件'
          },
          disabled: this.type === 'show' ? true: false,
        }
      ];
    },
    saveDialog () {
      let { preParams, whiteList, soVinId, recordVersion } = this
      let isTrue =  this.$refs.formPanel.SUBMIT_FORM();
      // console.log(preParams, this.saveData,"urls",this.formList)
      let saveData = null
      if (this.type === 'edit') {
        saveData = { ...preParams, ...this.saveData };
      } else {
        saveData = Object.assign({}, this.saveData);
      }
      whiteList.forEach(item => {
        saveData[item] = saveData[item].toString();
      })
      if (saveData['invoiceDate']) {
        // 当前时分秒的毫秒数
        let time = new Date().getTime() - new Date(moment().startOf('day')).getTime()
        saveData['invoiceDate'] = (new Date(saveData['invoiceDate']).getTime()+time).toString();
      }
      saveData['soVinId'] = soVinId
      saveData['recordVersion'] = recordVersion
      if(isTrue){
        postSoInvoice(saveData).then(res => {
          if (res.success) {
            this.closeDialog('refresh');
          } else {
            notifyAction(res.errMsg, 'error');
          }
        })
      }
    },

    formChangeHandle(val) {
      console.log('formChangeHandle',val)
      this.saveData = _.cloneDeep(val);
    },
    viNoSelect () {
      console.log('选择销售订单号')
      this.visible = true;
    },
    closeViNoHandler (val) {
      let { preDateHandler } = this
      console.log('回填销售单号', val);
      this.visible = false;
      if (val && val.length > 0) {
        this.soVinId = val[0].soVinId
        queryOrderVinInvoice (val[0].soVinId).then(res => {
          this.recordVersion = res.data['recordVersion']
          this.formList.forEach(item => {
            if (['urls'].includes(item.fieldName)) {
              // 什么也不做，因为没有这个字段
              // let urls = res.data['invoiceUrl']
              // if (urls && urls.length > 0) {
              //   let origin = urls.split('/');
              //   let fileName = origin[origin.length-1];
              //   x.initialValue.push({ name: fileName, url: item})
              // }
            } else if (item.fieldName == 'invoiceDate'){
              item.initialValue = preDateHandler(res.data['invoiceDate'])
            } else {
              item.initialValue = res.data[item.fieldName]
            }
          })
        })
      }
      // this.formList.find(item=> item.fieldName === 'viNo').initialValue = val[0].viNo;
    },
    // 日期预处理
    preDateHandler(val, formatCode='YYYY-MM-DD HH:mm:ss') {
      let resultDate = val ? moment(Number(val)).format(formatCode) : val;
      if ((resultDate == 'Invalid date' || resultDate == 'Invalid Date') && val) {
        resultDate = moment(val).format(formatCode)
      }
      return resultDate;
    },
    closeDialog (val = 'goBack') {
      this.$emit('close', false, val)
    },
  }
};
</script>

<style lang="less" scoped>
</style>

